﻿using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Net;
using System.Reflection;
using System.Net.NetworkInformation;

namespace WOTLauncher
{
    public partial class MainForm : Form
    {
        private const string WOT_XVM_PROCESS_NAME = "wot-xvm-proxy";
        private const string WOT_XVM_EXE_FILE_NAME = WOT_XVM_PROCESS_NAME + ".exe";
        private const string WOT_PROCESS_NAME = "WorldOfTanks";
        private const string WOT_CONFIG = "wot-xvm-proxy.exe.config";

        private static string wotXVMExeFileName = WOT_XVM_EXE_FILE_NAME;

        //http://www.***.com/CheckVersion?VER=2.4
        public static string VERSION_URL = "";
        public static string SUPPORT_URL = "*.html";
        public static string DOWNLOAD_URL = "*.html";
        public static string UPDATE = "UPDATE";

        private static string game_dir;
        private static string wotExeFileName = "WOTLauncher.exe";

        static RichTextBox logText = null;
        static Process wotProc = null;
        Thread logThread = null;
        private delegate void FlushClient();//代理

        public MainForm()
        {
            InitializeComponent();
            zoneComboBox.SelectedIndex = 0;
            radioButton1.Select();
            addLog();
            game_dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            Directory.SetCurrentDirectory(game_dir);
        }

        public bool CheckVersion()
        {
            try
            {
                WebRequest request = WebRequest.Create(VERSION_URL);
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Timeout = 3000;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);


                string responseFromServer = reader.ReadToEnd();
                if (responseFromServer.Equals(UPDATE))
                {
                    return true;
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                
            }
            return false;
        }


        private void addLog()
        {
            logText = new RichTextBox();
            logText.SetBounds(5, 175, 400, 135);
            logText.Size = new System.Drawing.Size(400, 135);
            logText.ReadOnly = true;
            logText.BackColor = System.Drawing.Color.White;

            this.Controls.Add(logText);
        }

        private void LaunchGameWithoutXVM()
        {
            try
            {
                using (Process wotProc = Process.Start(wotExeFileName))
                {
                    if (wotProc == null)
                    {
                        return;
                    }
                    Thread.Sleep(5000);
                    wotProc.WaitForExit();
                    if (wotProc.ExitCode == 0)
                    {
                        Console.WriteLine("Searching game process: " + WOT_PROCESS_NAME);
                        Thread.Sleep(5000);
                        Process[] wotProcesses = Process.GetProcessesByName(WOT_PROCESS_NAME);

                        if (wotProcesses.Length > 0)
                        {
                            wotProcesses[0].WaitForExit();
                        }
                    }
                }
            }
            catch
            {
                return;
            }

        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            String arg = "";

            if (radioButton2.Checked)
            {
                arg = "/launcher";
            }
            if (radioButton3.Checked)
            {
                arg = "/noauto";
            }

            if (radioButton4.Checked)
            {
                btnStart.Enabled = false;
                LaunchGameWithoutXVM();
                btnStart.Enabled = true;
                return;
            }

            int select = zoneComboBox.SelectedIndex;

            switch (select)
            {
                case 0:
                    arg += (" /server=CN1");
                    break;
                case 1:
                    arg += (" /server=CN2");
                    break;
            }
            execute(arg);
            
        }

        private void execute(string arg)
        {
            btnStart.Enabled = false;

            wotProc = new Process();
            if (wotProc == null)
                throw new Exception("Cannot start game: " + wotXVMExeFileName);
            wotProc.StartInfo.FileName = "cmd";
            wotProc.StartInfo.Arguments = "/k " + wotXVMExeFileName + arg;
            wotProc.StartInfo.UseShellExecute = false;
            wotProc.StartInfo.RedirectStandardInput = true;
            wotProc.StartInfo.RedirectStandardOutput = true;
            wotProc.StartInfo.CreateNoWindow = true;
            wotProc.Start();


            logThread = new Thread(CrossThreadFlush);
            logThread.Start();
            Thread.Sleep(1000);
        }

        private void CrossThreadFlush()
        {
            FlushClient fc = new FlushClient(logOutput);
            fc.BeginInvoke(null, null);
        }

        public void logOutput()
        {
            while (true)
            {

                StreamReader reader = wotProc.StandardOutput;
                string line = reader.ReadLine();
                logText.AppendText(line + System.Environment.NewLine);
                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine();
                    logText.AppendText(line + System.Environment.NewLine);
                    if (line.Equals("Dokan: Success"))
                    {
                        break;
                    }
                }

                wotProc.Close();
                reader.Close();
                logText.AppendText("Stopping log ..." + System.Environment.NewLine);
                this.btnStart.Enabled = true;

                Thread.Sleep(1000);
            }
        }

        public static Process GetRunningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess(); 

            string currentFileName = currentProcess.MainModule.FileName;
 
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);

            foreach (Process process in processes)
            {
                if (process.MainModule.FileName == currentFileName)
                {
                    if (process.Id != currentProcess.Id)
                        return process;
                }
            }
            return null;
        } 

        [DllImport("User32.dll")] 
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); 
        [DllImport("User32.dll")] 
        private static extern bool SetForegroundWindow(IntPtr hWnd); 
        
        private const int WS_SHOWNORMAL = 1;

        public static bool HandleRunningInstance(Process instance)
        {

            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);

            return SetForegroundWindow(instance.MainWindowHandle);
        }

        public static bool HandleRunningInstance()
        {
            Process p = GetRunningInstance();
            if (p != null)
            {
                HandleRunningInstance(p);
                return true;
            }
            return false;
        }

        private void logEnable_CheckedChanged(object sender, EventArgs e)
        {
            if (logEnable.Checked)
            {

                int hight = this.Size.Height;
                int width = this.Size.Width;
                this.Size = new System.Drawing.Size(width, hight+150);
            }
            else
            {

                int hight = this.Size.Height;
                int width = this.Size.Width;
                this.Size = new System.Drawing.Size(width, hight - 150);
            }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((logThread !=null)&&logThread.IsAlive)
            {
                logThread.Abort();
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            //if (CheckVersion())
            //{
            //    this.updateCheck.Text = "请升级到最新版";
            //    this.updateCheck.LinkColor = System.Drawing.Color.Red;
            //}
        }

        private void updateCheck_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                CheckVersionLink();
            }
            catch (Exception sus)
            {
                MessageBox.Show("Unable to open link that was clicked.");
            }
        }
        private void CheckVersionLink()
        {
            updateCheck.LinkVisited = true; System.Diagnostics.Process.Start(DOWNLOAD_URL);
        }

        private void supportXVM_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                supportLink();
            }
            catch (Exception sus)
            {
                MessageBox.Show("Unable to open link that was clicked.");
            }
        }

        private void supportLink()
        {
            supportXVM.LinkVisited = true; System.Diagnostics.Process.Start(SUPPORT_URL);
        }

        private void openReplay_Click(object sender, EventArgs e)
        {
            openReplay.Enabled = false;
            string arg = "";
            int select = zoneComboBox.SelectedIndex;

            switch (select)
            {
                case 0:
                    arg += (" /server=CN1");
                    break;
                case 1:
                    arg += (" /server=CN2");
                    break;
            }

            openReplayFileDialog.InitialDirectory = game_dir;
            openReplayFileDialog.Filter = "录像文件|*.wotreplay";
            openReplayFileDialog.RestoreDirectory = true;
            openReplayFileDialog.FilterIndex = 1;
            if (openReplayFileDialog.ShowDialog() == DialogResult.OK)
            {
                String fName = openReplayFileDialog.FileName;
                arg += (" " + fName);
                execute(arg);
            }
            openReplay.Enabled = true;
        }

        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {

        }

        public static string[] GetMacString()
        {
            string strMac = "";
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface ni in interfaces)
            {
                if (ni.OperationalStatus == OperationalStatus.Up)
                {
                    strMac += ni.GetPhysicalAddress().ToString() + "|";
                }
            }
            return strMac.Split('|');

        }

        private void VIPInfo_Click(object sender, EventArgs e)
        {
            string[] macs = GetMacString();
            logText.Clear();
            logText.AppendText(String.Join("",macs));
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
           
        }

        private void lnkGarphy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("Http://Garphy.com/tool/wot/");
        }
    }
}
